package service

import (
	"fmt"
	"github.com/go-admin-team/go-admin-core/sdk/service"
	"gorm.io/gorm"
	"tuowei.com/app/admin/models"
	dto2 "tuowei.com/app/teacher/service/dto"
	"tuowei.com/common/dto"
	"tuowei.com/pkg/xlog"
)

type UCenter struct {
	service.Service
}

func (u UCenter) Index(userId int) {
	// 获取跟进订单的数量(跟进状态就是财务审核状态)
	var followingCount int
	// 我邀请的学生数量
	var invitedCount int64
	// 我完成的订单数量
	var completeCount int
	// 总金额
	var totalIncome float64
	followingCount = models.OfflineOrder{}.GetStudentCount(u.Orm, userId, 3)
	completeCount = models.OfflineOrder{}.GetStudentCount(u.Orm, userId, 4)

	err := u.CountMyInvitedStudents(userId, &invitedCount)
	if err != nil {
		xlog.Error(err)
	}
	err = u.GetMyTotalIncome(userId, &totalIncome)
	if err != nil {
		xlog.Error(err)
	}
	xlog.Errorf("followingCount = %v", followingCount)
	xlog.Errorf("invitedCount = %v", invitedCount)
	xlog.Errorf("completeCount = %v", completeCount)
	xlog.Errorf("totalIncome = %v", totalIncome)

}

func (u UCenter) GetStudentsInvited(lists *[]models.SysStudent, count *int64, req dto.Pagination, teacherId int) error {
	err := u.Orm.Table(models.SysStudent{}.TableName()).
		Preload("College").Preload("Scores", func(tx *gorm.DB) *gorm.DB {
		return tx.Where("`change` = ?", 1).Order("buyer_id desc").Order("id desc")
	}).
		Scopes(
			dto.Paginate(req.GetPageSize(), req.GetPageIndex())).
		Where("teach_recommender = ?", teacherId).
		//teach_recommender enrollment_teacher_id
		Order("id desc").Find(lists).
		Count(count).
		Error
	return err
}

func (u UCenter) GetMyStudents(lists *[]models.SysStudent, count *int64, req *dto2.GetMyStudentsRequest, teacherId int) error {
	err := u.Orm.Table(models.SysStudent{}.TableName()).
		Scopes(
			dto.MakeCondition(req.GetNeedSearch()),
			dto.Paginate(req.GetPageSize(), req.GetPageIndex())).
		Where("teach_recommender = ? or enrollment_teacher_id = ?", teacherId, teacherId).
		//Or("enrollment_teacher_id = ?", teacherId).
		Order("id desc").Find(&lists).
		Count(count).
		Error
	return err
}

// 获取招生老师的总金额
func (u *UCenter) GetMyTotalIncome(userId int, total *float64) error {
	return u.Orm.Table(models.SysStudent{}.TableName()).
		Where("enrollment_teacher_id = ?", userId).
		Or("teach_recommender = ?", userId).Pluck("SUM(total_pay) as totalIncome", &total).Error

}

// 获取某个招生老师邀请的学员数量
func (u *UCenter) CountMyInvitedStudents(teacherId int, count *int64) error {
	return u.Orm.Table(models.SysStudent{}.TableName()).Where("enrollment_teacher_id = ?", teacherId).Count(count).Error
}

// 获取我邀请的学生的订单总数
func (u *UCenter) CountMyOfflineOrder(teacherId int, count *int64) error {
	return u.Orm.Table(models.OfflineOrder{}.TableName()).Raw(
		fmt.Sprintf("SELECT count(1) FROM sys_offline_order AS o INNER JOIN sys_student AS s "+
			"ON o.buyer_id = s.id "+
			"WHERE s.enrollment_teacher_id = %d ", teacherId)).
		Count(count).Error
}
